package com.stone.mythread;

/**
 * 线程同学的应用：生产者与消费者
 */
public class ProductTest {

    public static void main(String[] args) {
        Clerk clerk = new Clerk();

        Thread t1 = new Thread(new Producer(clerk));
        t1.setName("生产者1");

        Thread c1 = new Thread(new Consumer(clerk));
        c1.setName("消费者1");

        t1.start();
        c1.start();

    }

}

class Clerk {

    private int productCount = 0;

    // 生产产品
    public synchronized void produceProduct()  {
        if (productCount < 20) {
            productCount++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.err.println(Thread.currentThread().getName() + ":开始生产第 " + productCount + " 个产品。");
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 消费产品
    public synchronized void consumerProduct()  {
        if (productCount > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.err.println(Thread.currentThread().getName() + ": 开始消费第 " + productCount + " 个产品");
            productCount--;
            notify();
        } else {
            // 等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Producer implements Runnable { // 生产者

    private Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.err.println(Thread.currentThread().getName() + " : 开始生产产品");
        while (true) {
            clerk.produceProduct();
        }
    }
}

class Consumer implements Runnable { // 消费者

    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }


    @Override
    public void run() {
        System.err.println(Thread.currentThread().getName() + " : 开始消费产品");
        while (true) {
            clerk.consumerProduct();
        }
    }
}